//
//  MainViewController.swift
//  微博－01
//
//  Created by 程雷 on 15/6/23.
//  Copyright (c) 2015年 程雷. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        
//        //通过 kvc 设置 tarBar
//        let tb = MainTabBar()
//        setValue(tb, forKeyPath: "tabBar")
//        tb.compoesButton.addTarget(self, action: "compoesButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let w = tabBar.bounds.width/(CGFloat)(5)
        // TODO: 警告
        let rect = CGRectMake(0, 0, w, tabBar.bounds.height)
        compoesButton.frame = CGRectOffset(rect, 2*w, 0)
    }
    
    // 按钮的点击事件,按钮的点击方法不能设置为私有的
    func compoesButtonClick()
    {
        let nav = UINavigationController(rootViewController: ComposeViewController())
        presentViewController(nav, animated: true, completion: nil)
    }
    /**
    *  添加所有的字控制器"
    */
    
    private func addChildViewControllers(){
        
        addChildViewController(HomeTableViewController(),title:"首页",imageName:"tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        //中间 + 按钮
        addChildViewController(UIViewController(), title: "", imageName: nil)
        addChildViewController(HomeTableViewController(),title:"发现",imageName:"tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    /**
    添加控制器
    :param: vc        子控制器
    :param: title     标题
    :param: imageName 图片名称
    */
    private func addChildViewController(vc: UIViewController,title:String,imageName:String?) {
        
        vc.title = title
        if imageName != nil
        {
            vc.tabBarItem.image = UIImage(named: imageName!)
            vc.tabBarItem.selectedImage = UIImage(named: imageName!+"_highlighted")
        }
 
        
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
    
///  撰写代码
    private lazy var compoesButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // self. 闭包，提前准备好的代码，在需要的时候执行
        self.tabBar.addSubview(btn)
        // 按钮的监听方法
        btn.addTarget(self, action: "compoesButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
}

